<template>
    <div class="caih-register">
        <div class="caih-register-title">
            {{ props.title }}
            <span>{{ props.subTitle }}</span>
        </div>
        <div class="caih-register-content">
            <el-form ref="formRef" :model="form" :rules="rules">
                <el-form-item prop="username">
                    <UsernameTips>
                        <el-input
                            v-model="form.username"
                            placeholder="请输入用户名"
                            prefix-icon="el-icon-user"
                            clearable
                        />
                    </UsernameTips>
                </el-form-item>
                <Password ref="passwordRef" v-model="form.password" />
                <el-form-item prop="passwordConfirm">
                    <el-input
                        v-model="form.passwordConfirm"
                        type="password"
                        show-password
                        placeholder="请再次输入密码"
                        prefix-icon="el-icon-lock"
                        clearable
                    />
                </el-form-item>
                <el-form-item prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入手机号码" prefix-icon="el-icon-user" clearable />
                </el-form-item>
                <el-form-item prop="code">
                    <el-input
                        v-model="form.code"
                        placeholder="请输入验证码"
                        maxlength="6"
                        prefix-icon="el-icon-message"
                        clearable
                    >
                        <template #append>
                            <el-button :disabled="state.disabled" link @click="handleGetCode">
                                {{ state.codeText }}
                            </el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item v-if="props.agreement" prop="agreement">
                    <div class="agreement">
                        <el-checkbox-group v-model="form.agreement">
                            <el-checkbox label="请阅读并同意" name="type" />
                        </el-checkbox-group>
                        <span @click="emits('agreement')">《{{ props.agreement }}》</span>
                    </div>
                </el-form-item>
                <el-button class="btn-register" type="primary" @click="handleRegister">注册</el-button>
            </el-form>
            <div v-if="Boolean(props.login)" class="link-login" @click="handleClickLogin">
                已有账号登录
                <el-icon><el-icon-right /></el-icon>
            </div>
        </div>
        <Captcha
            ref="captchaRef"
            v-model:disabled="state.disabled"
            v-model:text="state.codeText"
            unique-key="register"
            keep-running
            :duration="props.smsDelay"
        />
    </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";

import Password from "@/components/password/index.vue";
import Captcha from "@/components/captcha.vue";
import UsernameTips from "./components/username-tips.vue";

const router = useRouter();

const emits = defineEmits(["register", "agreement"]);
const props = defineProps({
    title: { type: String, default: "注册" },
    subTitle: { type: String, default: "REGISTER" },
    login: { type: [String, Function], default: "" },
    agreement: { type: String, default: "" },
    smsDelay: { type: [String, Number], required: true },
    getSmsCode: { type: Function, required: true },
});
const captchaRef = ref(null);
const formRef = ref(null);
const passwordRef = ref(null);
const form = reactive({
    username: "",
    password: "",
    passwordValid: false,
    passwordConfirm: "",
    phone: "",
    code: "",
    agreement: [],
});
const state = reactive({ disabled: false, codeText: "" });

const rules = {
    username: { required: true, message: "请输入用户名" },
    // password: { required: true, message: "请输入密码" },
    passwordConfirm: [
        { required: true, message: "请再次输入密码" },
        { validator: (_, value) => value === form.password, message: "两次输入密码必须保持一致，请重新输入" },
    ],
    phone: [
        { required: true, message: "请输入手机号码" },
        {
            validator: async (_, value) =>
                /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)
                    ? Promise.resolve()
                    : Promise.reject("手机号格式不正确"),
        },
    ],
    code: [
        { required: true, message: "请输入验证码" },
        { len: 6, message: "请输入6位数验证码" },
    ],
    agreement: [{ required: true, type: "array", message: "请阅读并同意协议" }],
};

const getSmsCodeCallback = (status) => {
    if (status) {
        captchaRef.value.start();
    }
};

const handleGetCode = async () => {
    const checkPhone = await formRef.value.validateField("phone").catch(() => {});
    if (!checkPhone) return;

    if (captchaRef.value.disabled) return;

    const fn = props.getSmsCode(form.phone, getSmsCodeCallback);
    let status = null;

    if (fn instanceof Promise) {
        status = await fn;
        if (status !== void 0) getSmsCodeCallback(status);
    }
};

const handleRegister = async () => {
    const fns = [passwordRef.value.validate(), formRef.value.validate()];
    const status = await Promise.all(fns).catch(() => {});
    if (!status) return;

    const { username, password, phone, code, agreement } = form;
    emits("register", { username, password, phone, code, agreement: Boolean(agreement.length) });
};

const handleClickLogin = () => {
    if (typeof props.login === "string") {
        router.push(props.login);
    } else if (typeof props.login === "function") {
        props.login();
    }
};
</script>

<style lang="scss" scoped>
.caih-register {
    width: 416px;
    padding: 48px 43px;
    background: #fff;
    box-sizing: border-box;
    .caih-register-title {
        display: flex;
        align-items: center;
        height: 26px;
        font-size: 20px;
        font-weight: 700;
        color: rgba(0, 0, 0, 0.85);
        margin-bottom: 32px;
        span {
            margin-left: 8px;
            color: rgba(0, 0, 0, 0.25);
        }
    }
    .caih-register-content {
        .agreement {
            display: flex;
            span {
                color: var(--el-color-primary);
                cursor: pointer;
            }
        }
        .btn-register {
            width: 100%;
        }
        .link-login {
            display: flex;
            align-items: center;
            color: var(--el-color-primary);
            font-size: 14px;
            text-decoration: none;
            margin-top: 24px;
            cursor: pointer;
            :deep(.el-icon) {
                margin-left: 8px;
            }
        }
    }
}
</style>
